package com.odm.communitymanage.ui.mine.MyIdle

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.jeremyliao.liveeventbus.LiveEventBus
import com.odm.communitymanage.R
import com.odm.communitymanage.base.BaseMVVMFragment
import com.odm.communitymanage.core.Constants
import com.odm.communitymanage.core.bean.MyIdles
import com.odm.communitymanage.core.net.ApiService
import com.odm.communitymanage.ui.activity.ActivitiesDiffCallback
import com.rxjava.rxlife.lifeOnMain
import com.zhengsr.tablib.view.adapter.TabFlowAdapter
import com.zhengsr.tablib.view.flow.TabFlowLayout
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.fragment_my_idle.*
import rxhttp.asClass
import rxhttp.wrapper.param.RxHttp

/**
 * @description: 我的闲置 页面
 * @author: ODM
 * @date: 2020/4/15
 */
class MyIdleFragment : BaseMVVMFragment(){

    private var rvAdapter : MyIdleAdapter ?= null

    private var disposable : Disposable ?= null


    override fun onLazyInitView(savedInstanceState: Bundle?) {
        super.onLazyInitView(savedInstanceState)
        //获取 第一个tab 发布闲置 后的数据
        getMyPostIdlesData()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        if(disposable?.isDisposed == false){
            disposable?.dispose()
        }
    }


    override fun initViewModelObserve() {

    }

    override fun initViews() {

        initTabLayout()

        initRecyclerView()

        ivBack_MyIdle.setOnClickListener {
            pop()
        }
    }

    private fun initRecyclerView(){
        // 初始化 recyclerView 和 适配器
        rvMyIdles.layoutManager = LinearLayoutManager(requireContext())
        rvAdapter = MyIdleAdapter(mutableListOf())
        rvMyIdles.adapter = rvAdapter
        rvAdapter?.animationEnable = true
        //设置空布局
        rvAdapter?.setEmptyView(R.layout.layout_empty_list)
        rvAdapter?.setAnimationWithDefault(BaseQuickAdapter.AnimationType.SlideInBottom)
        rvAdapter?.setOnItemClickListener{ adapter, view, position ->
            LiveEventBus
                .get(Constants.EVENT_MY_IDLE_DETAIL)
                .post(rvAdapter?.data?.get(position))
            start(MyIdleDetailFragment())
        }
    }

    /**
     * 请求获取 我发布的闲置数据
     */
    private fun getMyPostIdlesData(){
       disposable = RxHttp.get(ApiService.MY_IDLE_LIST)
            .asClass(MyIdles::class.java)
            .lifeOnMain(this)
            .subscribe({
                if(it.code == 1 && it.data.isNotEmpty()){
                    // 列表数据为空，显示空状态布局
                    // 列表数据不为空根据Adapter数据引用判断使用setList/setDiffNewData
                        msv_my_idle?.showContent()
                        if( rvAdapter?.data?.isEmpty() == true ){
                            rvAdapter?.setList(it.data.toMutableList())
                        }else {
                            rvAdapter?.setDiffNewData(
                                DiffUtil.calculateDiff(MyIdleDiffCallback(rvAdapter?.data, it.data)) ,
                                it.data.toMutableList()
                            )
                        }
                }else {
                    msv_my_idle.showEmpty()
                    ToastUtils.showShort(it.message)
                }
            },{
                msv_my_idle.showError()
                ToastUtils.showShort(it.message)
            })
    }

    /**
     * 根据假数据，显示我的购买闲置列表
     */
    private fun getFakeMyBoughtIdle(){
        val fakeBoughtData : MyIdles = GsonUtils.fromJson( "{\"message\":\"success\",\"code\":\"1\",\"data\":[{\"id\":1,\"topic\":\"123456\",\"price\":123.4,\"description\":\"123456\",\"imgs\":[\"http://img5.imgtn.bdimg.com/it/u=1185956659,3974949794&fm=26&gp=0.jpg\",\"http://img5.imgtn.bdimg.com/it/u=1185956659,3974949794&fm=26&gp=0.jpg\"],\"remarks\":\"123456\",\"userName\":\"张三\",\"phone\":\"1992735992\",\"time\":\"2020-04-16 22:54:17\",\"status\":1},{\"id\":1,\"topic\":\"123456\",\"price\":123.4,\"description\":\"123456\",\"imgs\":[\"http://img0.imgtn.bdimg.com/it/u=2027111206,545813762&fm=26&gp=0.jpg\",\"http://img0.imgtn.bdimg.com/it/u=2027111206,545813762&fm=26&gp=0.jpg\"],\"remarks\":\"123456\",\"userName\":\"李四\",\"phone\":\"19923735673\",\"time\":\"2020-04-26 22:54:15\",\"status\":1}]}"
            , MyIdles::class.java)
        msv_my_idle.showContent()
        if(rvAdapter?.data?.isEmpty() == true || fakeBoughtData.data.isEmpty()){
            rvAdapter?.setList(fakeBoughtData.data.toMutableList())
        } else {
            rvAdapter?.setDiffNewData(
                DiffUtil.calculateDiff(MyIdleDiffCallback(rvAdapter?.data, fakeBoughtData.data)) ,
                fakeBoughtData.data.toMutableList()
            )
        }
    }

    /**
     * 初始化 TabLayout
     */
    private fun initTabLayout(){
        //TabLayout点击事件
        tabMyIdle?.configTabLayoutConfig {
            //选中项的view的回调
            onSelectViewChange = { fromView, selectViewList, reselect ->
                val toView = selectViewList.first()
                if (reselect) {
                    //重复选择
                }
            }
            //选中项index的回调事件--显示不同排序的瀑布流List
            onSelectIndexChange = { fromIndex, selectIndexList, reselect ->
                //toIndex 为 选中 Index
                val toIndex = selectIndexList.first()
                when(toIndex){
                    0 -> {
                        msv_my_idle.showLoading()
                        getMyPostIdlesData()
                    }
                    1 -> {
                        msv_my_idle.showLoading()
                        getFakeMyBoughtIdle()
                    }
                    else -> {}
                }
            }
        }
    }
    
    


    override fun getLayoutId(): Int {
        return R.layout.fragment_my_idle
    }

}